angular.module('ProductDisplay')
    .controller('ProductDisplay.ProductDisplayCtrl', ['$scope', '$filter', '$state', '$interval', '$ionicLoading', '$ionicPopup', '$stateParams', 'Http', 'imanDialog', 'Device', 'User', 'Help', 'ProductDisplay.Service',
        function ($scope, $filter, $state, $interval, $ionicLoading, $ionicPopup, $stateParams, Http, imanDialog, Device, User, Help, ProductService) {
            $scope.data = {
                finishCount: 0,
                totalCount: 0,
                departmentName: '请选择部门'
            };
            var t;

            $scope.data.gridOptions = {
                columnDefs: [],
                data: []
            };

            $scope.$on('$ionicView.afterEnter', function () {
                angular.element(document).keydown(onkeydown);
                // $scope.data = {
                //     finishCount: 0,
                //     totalCount: 0
                // };
                getData();
                t = $interval(function() {
                    getData();
                }, 30000);
            });

            $scope.$on('$ionicView.beforeLeave', function () {
                angular.element(document).off('keydown', onkeydown);
                $interval.cancel(t);
            });

            $scope.$on('$destroy', function () {
                ProductService.resetDefault();
            });

            $scope.goDepartmentList = function () {
                $state.go('Department');
            };

            function onkeydown(event) {
                var keyCode = event.keyCode;
                if (keyCode === 13) { // 确认
                    $state.go('Department');
                }
            }

            function getData(){
                $scope.data.finishCount= 0;
                $scope.data.totalCount= 0;
                if (ProductService.getDepartment()) {
                    $scope.data.departmentName = ProductService.getDepartment().department;
                    var flg = true;
                    ProductService.queryDepartment(ProductService.getDepartment().id).then(function (records) {
                        var departArr = [],departCodeArr=[];
                        if (records.length > 0) {//所选部门下有产线
                            angular.forEach(records, function (record) {
                                departArr.push(record._id);
                                departCodeArr.push(record.Code);
                            });
                            flg = true;
                        } else {//没产线
                            departArr.push(ProductService.getDepartment().id);
                            flg = false;
                        }
                        ProductService.queryWorkLocation(departArr).then(function (res) {
                            var workLocationArr = [], wlCode = [];

                            angular.forEach(res, function (obj) {
                                workLocationArr.push(obj._id);
                                wlCode.push(obj.Code);
                            });

                            ProductService.countProductView(workLocationArr, flg).then(function (result) {
                                    var finalData = [], lCode = [], t = {}, ct = {},
                                        tempSum = {
                                            key: '汇总'
                                        }, tempOrder = {
                                            key: '排名'
                                        };
                                    var titleCol = [{col: 'key', name: '型号'}];
                                    angular.forEach(result.total, function (total, key) {
                                        lCode.push(key);
                                    });
                                    if (lCode.length === 0) {
                                        $scope.data.totalCount = 0;
                                        $scope.data.finishCount = 0;
                                    }
                                    if (flg) {//1。部门列表,(型号,部门,数量  可能又重复,需要循环)
                                        for (var ii = 0; ii < lCode.length; ii++) {
                                            var tmpTrue = {
                                                key: lCode[ii]
                                            }, totalSumTrue = 0, completeSumTrue = 0;
                                            for (var jj = 0; jj < departCodeArr.length; jj++) {
                                                if (result.total[lCode[ii]] && result.total[lCode[ii]][departCodeArr[jj]]) {
                                                    tmpTrue[departCodeArr[jj]] = result.total[lCode[ii]][departCodeArr[jj]];

                                                    if (t[departCodeArr[jj]]) {
                                                        t[departCodeArr[jj]] += result.total[lCode[ii]][departCodeArr[jj]];
                                                    } else {
                                                        t[departCodeArr[jj]] = result.total[lCode[ii]][departCodeArr[jj]];
                                                    }

                                                    $scope.data.totalCount += result.total[lCode[ii]][departCodeArr[jj]];

                                                    totalSumTrue += result.total[lCode[ii]][departCodeArr[jj]];
                                                    if (result.complete[lCode[ii]] && result.complete[lCode[ii]][departCodeArr[jj]]) {
                                                        tmpTrue[departCodeArr[jj]] += '<span style="color: #000000">(</span><span style="color: #069668">' + result.complete[lCode[ii]][departCodeArr[jj]] + '</span><span style="color: #000000">)</span>';
                                                        completeSumTrue += result.complete[lCode[ii]][departCodeArr[jj]];
                                                        if (ct[departCodeArr[jj]]) {
                                                            ct[departCodeArr[jj]] += result.complete[lCode[ii]][departCodeArr[jj]];
                                                        } else {
                                                            ct[departCodeArr[jj]] = result.complete[lCode[ii]][departCodeArr[jj]];
                                                        }
                                                        $scope.data.finishCount += result.complete[lCode[ii]][departCodeArr[jj]];
                                                    } else {
                                                        tmpTrue[departCodeArr[jj]] += '<span style="color: #000000">(</span><span style="color: #069668">' + 0 + '</span><span style="color: #000000">)</span>';
                                                        completeSumTrue += 0;
                                                    }
                                                } else {
                                                    tmpTrue[departCodeArr[jj]] = '';
                                                    $scope.data.totalCount += 0;
                                                    $scope.data.finishCount += 0;
                                                }

                                            }
                                            tmpTrue['sumCount'] = totalSumTrue + '<span style="color: #000000">(</span><span style="color: #069668">' + completeSumTrue + '</span><span style="color: #000000">)</span>';
                                            finalData.push(tmpTrue);

                                        }
                                        for (var mm = 0; mm < departArr.length; mm++) {
                                            if (t[departCodeArr[mm]]) {
                                                tempSum[departCodeArr[mm]] = t[departCodeArr[mm]];
                                                if (ct[departCodeArr[mm]]) {
                                                    tempSum[departCodeArr[mm]] += '<span style="color: #000000">(</span><span style="color: #069668">' + ct[departCodeArr[mm]] + '</span><span style="color: #000000">)</span>';
                                                }
                                            }
                                        }
                                        angular.forEach(records, function (obj) {
                                        if (t[obj.Code]) {
                                                titleCol.push({col: obj.Code, name: obj.Name});
                                            }
                                        });
                                    } else {//2。工位列表,(型号,工位,数量  可能又重复,需要循环)
                                        for (var i = 0; i < lCode.length; i++) {
                                            var tmp = {
                                                key: lCode[i]
                                            }, totalSum = 0, completeSum = 0;
                                            for (var j = 0; j < wlCode.length; j++) {
                                                if (result.total[lCode[i]] && result.total[lCode[i]][wlCode[j]]) {
                                                    tmp[wlCode[j]] = result.total[lCode[i]][wlCode[j]];

                                                    if (t[wlCode[j]]) {
                                                        t[wlCode[j]] += result.total[lCode[i]][wlCode[j]];
                                                    } else {
                                                        t[wlCode[j]] = result.total[lCode[i]][wlCode[j]];
                                                    }

                                                    $scope.data.totalCount += result.total[lCode[i]][wlCode[j]];

                                                    totalSum += result.total[lCode[i]][wlCode[j]];
                                                    if (result.complete[lCode[i]] && result.complete[lCode[i]][wlCode[j]]) {
                                                        tmp[wlCode[j]] += '<span style="color: #000000">(</span><span style="color: #069668">' + result.complete[lCode[i]][wlCode[j]] + '</span><span style="color: #000000">)</span>';
                                                        completeSum += result.complete[lCode[i]][wlCode[j]];
                                                        if (ct[wlCode[j]]) {
                                                            ct[wlCode[j]] += result.complete[lCode[i]][wlCode[j]];
                                                        } else {
                                                            ct[wlCode[j]] = result.complete[lCode[i]][wlCode[j]];
                                                        }
                                                        $scope.data.finishCount += result.complete[lCode[i]][wlCode[j]];
                                                    } else {
                                                        tmp[wlCode[j]] += '<span style="color: #000000">(</span><span style="color: #069668">' + 0 + '</span><span style="color: #000000">)</span>';

                                                        completeSum += 0;
                                                    }
                                                } else {
                                                    tmp[wlCode[j]] = '';
                                                    $scope.data.totalCount += 0;
                                                    $scope.data.finishCount += 0;
                                                }

                                            }
                                            tmp['sumCount'] = totalSum + '<span style="color: #000000">(</span><span style="color: #069668">' + completeSum + '</span><span style="color: #000000">)</span>';
                                            finalData.push(tmp);
                                        }

                                        for (var m = 0; m < wlCode.length; m++) {
                                            if (t[wlCode[m]]) {
                                                tempSum[wlCode[m]] = t[wlCode[m]];
                                                if (ct[wlCode[m]]) {
                                                    tempSum[wlCode[m]] += '<span style="color: #000000">(</span><span style="color: #069668">' + ct[wlCode[m]] + '</span><span style="color: #000000">)</span>';
                                                }
                                            }
                                        }

                                        angular.forEach(res, function (obj) {
                                        if (t[obj.Code]) {
                                                titleCol.push({col: obj.Code, name: obj.Name});
                                            }
                                        });
                                    }
                                    var TTemp = [];
                                    angular.forEach(t, function (value, key) {
                                        TTemp.push({key: key, value: value});
                                    });

                                    function formatRank (rank) {
                                        return rank < 4 ? '<span style="color: #d71700">' + rank + '</span>' : rank;
                                    }

                                    TTemp = $filter('orderBy')(TTemp, 'value', -1);
                                    var index = 0, lastTemp = {};
                                    for (var p = 0; p < TTemp.length; p++) {

                                        if (TTemp[p].value === lastTemp.value) {
                                            if (ct[TTemp[p].key] > ct[lastTemp.key]) {
                                                tempOrder[[TTemp[p].key]] = formatRank(index);
                                                tempOrder[lastTemp.key] = formatRank(index + 1);
                                                index++;
                                            } else if (ct[TTemp[p].key] < ct[lastTemp.key]) {
                                                tempOrder[[TTemp[p].key]] = formatRank(index + 1);
                                                index++;
                                            } else {
                                                tempOrder[[TTemp[p].key]] = formatRank(index);
                                            }
                                        } else {
                                            index++;
                                            tempOrder[[TTemp[p].key]] = formatRank(index);
                                        }
                                        lastTemp = TTemp[p];
                                    }
                                    finalData.push(tempSum);
                                    finalData.push(tempOrder);
                                    
                                    
                                    titleCol.push({col: 'sumCount', name: '汇总'});
                                    $scope.data.gridOptions.columnDefs = titleCol;
                                    $scope.data.gridOptions.data = finalData;
                                }
                            );
                        });
                    });
                }
            }
        }
    ]);
